package com.dxh.client;

import com.dxh.handler.UserClientHandler;
import com.dxh.service.JSONSerializer;
import com.dxh.service.RpcEncoder;
import com.dxh.service.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: Dengxh
 * @Date: 2021/1/17 17:41
 * @Description:
 */
public class RPCConsumer {
    //创建一个线程池对象 -- 他要处理自定义事件
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    //声明一个自定义事件处理器 UserClientHandler
    private static UserClientHandler userClientHandler;
    //初始化客户端 （创建连接池、bootStrap、设置bootStrap 、连接服务器）
    public static void initClient() throws InterruptedException {
        //初始化UserClientHandler
        userClientHandler = new UserClientHandler();
        //创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //创建客户端的引导对象
        Bootstrap bootstrap = new Bootstrap();
        //配置启动引导类
        bootstrap.group(group).channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY,true)
                //监听channel并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
        //连接服务端
        bootstrap.connect("127.0.0.1",8999).sync();
    }

    //编写方法，使用jdk动态代理创建对象
    //serviceClass 接口类型，根据哪个结构生成子类代理对象； providerParam：”userService#sayHello#“
    public  Object createProxy(Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 初始化客户端client
                if (userClientHandler == null){
                    initClient();
                }
                // 封装
                RpcRequest rpcRequest = new RpcRequest();
                String requestId = UUID.randomUUID().toString();
                System.out.println("RequestId : "+requestId);

                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();

                Class<?>[] parameterTypes = method.getParameterTypes();
                rpcRequest.setRequestId(requestId);
                rpcRequest.setClassName(className);
                rpcRequest.setMethodName(methodName);
                rpcRequest.setParameters(args);
                rpcRequest.setParameterTypes(parameterTypes);

                userClientHandler.setParam(rpcRequest);
                System.out.println(rpcRequest);
                System.out.println("设置参数完成");

                //去服务端请求数据
                return executorService.submit(userClientHandler).get();
            }
        });
    }
}